/*
 * Copyright (C) 2018 Tom Li <tomli at tomli.me>.
 *
 * This software is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option) any
 * later version.
 *
 * This software is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See COPYING for terms and conditions.
 *
 * GPL or LGPL does __not__ require attribution beyond preserving and
 * following the license, but if you find my code is useful or inspirational
 * to your own project, I'd be thankful if you attribute my name.
 */

#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{
    FILE *f;
    FILE *f2;
    long size;

    char name[256];

    if (argc != 2) {
        fprintf(stderr, "error: too many or no argument, should be\n");
        fprintf(stderr, "%s [A INPUT FILE]\n", argv[0]);
        return 1;
    }

    strncpy(name, argv[1], 64);
    name[64] = '\0';

    f = fopen(name, "rb");
    fseek(f, 0, SEEK_END);
    size = ftell(f);
    fseek(f, 1, SEEK_SET);

    strcat(name, ".rgb565");
    f2 = fopen(name, "w+");

    //printf("size: %lu\n", size);

    uint16_t r, g, b;
    uint16_t color;
    uint8_t done = 0;

    for (long i = 1; i < size; i += 3) {
        done |= !fread(&r, 1, 1, f);
        done |= !fread(&g, 1, 1, f);
        done |= !fread(&b, 1, 1, f);
        if (done) {
            break;
        }

        b = (((uint8_t) b) >> 3) & 0x1F;
        g = ((((uint8_t) g) >> 2) & 0x3F) << 5;
        r = ((((uint8_t) r) >> 3) & 0x1F) << 11;
        color = (r | g | b);

        fwrite(&color, sizeof(color), 1, f2);
    }

    fclose(f);
    fclose(f2);
}
